package com.pms.web;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.controller.BaseController;
import com.pms.entity.AreaCommunity;
import com.pms.entity.BaseModel;
import com.pms.entity.BaseUserInfo;
import com.pms.entity.Community;
import com.pms.exception.R;
import com.pms.exception.RRException;
import com.pms.result.TableResultResponse;
import com.pms.rpc.AreaCnService;
import com.pms.rpc.UserService;
import com.pms.service.IAreaCommunityService;
import com.pms.service.ICommunityService;
import com.pms.utils.LBSUtil;
import com.pms.validator.Assert;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 * 社区（小区）表 前端控制器
 * </p>
 *
 * @author lk
 * @since 2017-12-25
 */
@RestController
@RequestMapping("/pms/community")
public class CommunityController extends BaseController {
    @Autowired
    ICommunityService communityService;
    @Autowired
    UserService userService;
    @Autowired
    IAreaCommunityService areaCommunityService;
    @Autowired
    AreaCnService areaCnService;
    @Autowired
    private LBSUtil lBSUtil;
    /**
     * 添加小区（社区）信息
     * 添加正则验证 社区名称不能有_
     * @param
     * @return
     */
    @ApiOperation(value = "添加小区（社区）信息")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="communityName",value="小区名称",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="communityAddress",value="小区地址",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="areaGb",value="对应的区域编号(县/区级)",required = true,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="areaName",value="对应的区域名称(县/区级)",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name = "longitude", value = "经度值", required = true, dataType = "double", paramType = "form"),
            @ApiImplicitParam(name = "latitude", value = "纬度值", required = true, dataType = "double", paramType = "form"),
    })
    public R add(Double longitude,Double latitude,String communityName, String communityAddress, Integer areaGb, String areaName){
        Assert.isBlank(communityName,"小区名称不能为空");
        Assert.isBlank(communityAddress,"小区地址不能为空");
        parameterIsNull(areaGb,"请选择区域");
        if(longitude==null||latitude==null){
            return R.error(400,"地址经纬度信息不能为空");
        }
        Assert.isBlank(areaName,"区域名称不能为空");
        communityName = communityName.trim();
        Long communitySort = communityService.selectMaxCommunitySort();
        Community community = new Community();
        community.setCommunityName(communityName);
        community.setAreaGb(areaGb);
        community.setAreaName(areaName);
        community.setCommunityAddress(communityAddress);
        community.setCommunitySort(communitySort+1);//最大的社区排序加1
        community.setCommunityId(BaseModel.returnStaticIdLong());
        community.setCreateTime(new Date());
        Map<String, Object> lbsParamMap = new HashMap<String, Object>();
        lbsParamMap.put("ak", lBSUtil.getAK());
        lbsParamMap.put("geotable_id", lBSUtil.getCommunityGeotableId());
        lbsParamMap.put("coord_type", 3);//坐标类型
        lbsParamMap.put("longitude", longitude);//经度
        lbsParamMap.put("latitude", latitude);//纬度
        lbsParamMap.put("address", communityAddress);//地址
        lbsParamMap.put("title", communityName);//poi名称
        lbsParamMap.put("communityId", community.getCommunityId());//poi名称
        lbsParamMap.put("communityName", communityName);//poi名称
        JSONObject lbsJson = LBSUtil.poiCreateByMap(lbsParamMap);
        if (!lbsJson.getString("status").equals("0")) {
            logger.error("店铺LBS添加poi数据出错，返回信息:");
            logger.error(lbsJson.toString());
            return R.error("请求参数格式出错");
        }
        community.setLbsPoiId(lbsJson.getString("id"));//设置Lbs区域id
        community.setLongitude(longitude);
        community.setLatitude(latitude);
        communityService.insert(community);
        Map<String,Object> area = areaCnService.getcounty(areaGb);
        if (area.isEmpty()){ throw  new RRException("地址信息不存在",400);  }
        AreaCommunity areaCommunity=new AreaCommunity();
        areaCommunity.setCityName(area.get("cityName").toString());//市级地址
        areaCommunity.setCityGb(Integer.parseInt(area.get("cityGb").toString()));//市级编码
        areaCommunity.setCreateTime(new Date());
        areaCommunity.setCountyGb(areaGb);//区县级编码
        areaCommunity.setCountyName(areaName);//区县级名称
        areaCommunity.setCommunityId(community.getCommunityId());//小区ID
        areaCommunityService.insert(areaCommunity);
        return R.ok();
    }

    /**
     * 删除小区（社区）信息
     * @param
     * @return
     */
    @ApiOperation(value = "删除小区（社区）信息")
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="communityId",value="小区id",required = true,dataType = "Long",paramType="form")
    })
    public R delete(Long communityId){
        parameterIsNull(communityId,"社区ID不能为空");
        Community community = communityService.selectById(communityId);
        Assert.isNull(community,"没有此小区");
        communityService.deleteCommunityAndWaterPumps(communityId);
        Map<String, Object> lbsParamMap = new HashMap<String, Object>();
        lbsParamMap.put("ak", lBSUtil.getAK());
        lbsParamMap.put("geotable_id", lBSUtil.getCommunityGeotableId());
        lbsParamMap.put("id",community.getLbsPoiId());
//        JSONObject lbsJson = LBSUtil.poiCreate(longitude,latitude,shopAddress,shopName,shopSignage);
        JSONObject lbsJson = LBSUtil.poiDeleteByMap(lbsParamMap);
        return R.ok();
    }

    /**
     * 编辑小区（社区）信息
     * @param
     * @return
     */
    @ApiOperation(value = "编辑小区（社区）信息")
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="communityId",value="小区id",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="communityName",value="小区名称",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="communityAddress",value="小区地址",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="areaGb",value="所属区域id",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="areaName",value="对应的区域名称(县/区级)",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name = "longitude", value = "经度值", required = false, dataType = "double", paramType = "form"),
            @ApiImplicitParam(name = "latitude", value = "纬度值", required = false, dataType = "double", paramType = "form"),
    })
    public R update(Double longitude,Double latitude,Long communityId, String communityName, String communityAddress, Integer areaGb, String areaName){
        Assert.isNull(communityId,"小区id不能为空");
        Community community = communityService.selectById(communityId);
        Assert.isNull(community,"没有此小区");
        Map<String, Object> lbsParamMap = new HashMap<String, Object>();
        if(!StringUtils.isEmpty(communityName)){
            community.setCommunityName(communityName);
            lbsParamMap.put("communityName",communityName);
            lbsParamMap.put("title", communityName);//poi名称
        }
        if(!StringUtils.isEmpty(communityAddress)){
            community.setCommunityAddress(communityAddress);
//            lbsParamMap.put("address", communityAddress);//地址
        }
        if(!StringUtils.isEmpty(areaName)){
            community.setAreaName(areaName);
        }
        if(longitude!=null&&latitude!=null){
            lbsParamMap.put("longitude", longitude);//经度
            lbsParamMap.put("latitude", latitude);//纬度
            community.setLongitude(longitude);
            community.setLatitude(latitude);
            lbsParamMap.put("address", community.getCommunityAddress());//经度
        }
        community.setUpdateTime(new Date());
        if(areaGb!=null){
            community.setAreaGb(areaGb);
        }
        communityService.updateById(community);
        if(areaGb!=null){
            AreaCommunity  areaCommunity=areaCommunityService.selectOne(new EntityWrapper<AreaCommunity>().eq("community_id",communityId));
            parameterIsNull(areaCommunity,"区县地址不存在");
            Map<String,Object> area = areaCnService.getcounty(areaGb);
            if (area.isEmpty()){ throw  new RRException("地址信息不存在",400);  }
            areaCommunity.setCityName(area.get("cityName").toString());//市级
            areaCommunity.setCountyName(area.get("countyName").toString());//县级
            areaCommunity.setCityGb(Integer.parseInt(area.get("cityGb").toString()));//市级编码
            areaCommunity.setCountyGb(areaGb);//区县级编码
            areaCommunityService.updateAllColumnById(areaCommunity);
        }
        if(!lbsParamMap.isEmpty()){//同步修改  百度lbs 社区表
            lbsParamMap.put("ak", lBSUtil.getAK());
            lbsParamMap.put("geotable_id", lBSUtil.getCommunityGeotableId());
            lbsParamMap.put("coord_type", 3);
            lbsParamMap.put("id", community.getLbsPoiId());
            LBSUtil.poiUpdateByMap(lbsParamMap);
        }
        return R.ok();
    }

    /**
     * 查询用户权限下的小区（社区）信息
     * @param
     * @return
     */
    @ApiOperation(value = "查询用户权限下的小区（社区）信息")
    @RequestMapping(value = "/query",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="userId",value="用户id",required = true,dataType = "Long",paramType="form"),
    })
    public R query(Long userId){
        parameterIsNull(userId,"用户ID不能为空");
        BaseUserInfo baseUserInfo = userService.getUserByUserId(userId);
        Assert.isNull(baseUserInfo,"没有此用户");
        Wrapper<Community> wp = new EntityWrapper<Community>();
        Long communityId = baseUserInfo.getCommunityId();
        List<Community> communityList = new ArrayList<Community>();
        if(communityId!=null){
            wp.eq("community_id",communityId);//用户带社区id，直接查此社区
        }else{
            Long areaId = baseUserInfo.getAreaId();
            Long companyId = baseUserInfo.getCompanyId();
            if(areaId==null&&companyId==null){
                //查询所有
            }else if(companyId!=null&&areaId!=null){
                wp.eq("company_id",companyId);
                wp.eq("area_id",areaId);//查询这个公司这个区域内的社区
            }else if(companyId!=null&&areaId==null){
                wp.eq("company_id",companyId);
            }else if(companyId!=null&&areaId!=null){
                throw  new RRException("用户信息有误",400);            }
        }
        communityList = communityService.selectList(wp);
        return R.ok().put("communityList",communityList);
    }

    /**
     * 根据社区id查询小区（社区）信息
     * @param
     * @return
     */
    @ApiOperation(value = "根据社区id查询小区（社区）信息")
    @RequestMapping(value = "/queryById",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="communityId",value="对应的社区id",required = true,dataType = "Long",paramType="form")
    })
    public R queryById(Long communityId){
        parameterIsNull(communityId,"社区ID不能为空");
        Community community = communityService.selectById(communityId);
        Assert.isNull(community,"没有此社区");
        return R.ok().put("community",community);
    }
    /**
     * 分页查询
     * @param limit
     * @param page
     * @param communityName
     * @return
     */
    @RequestMapping(value = "/page",method = RequestMethod.GET)
    public TableResultResponse<Community> page(Integer limit, Integer page, String communityName){
        if (limit==null){limit=10;}
        if (page==null){page=1;}
        Page<Community> pages = new Page<Community>(page,limit);
        pages = communityService.selectPage(pages,new EntityWrapper<Community>().like("community_name",communityName));
        if (pages==null){
            return new TableResultResponse<Community>();
        }else{
            return new TableResultResponse<Community>(pages.getTotal(),pages.getRecords());
        } }


}
